package org.ielts.action.security;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.ielts.service.security.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.yifeng.modules.annotations.Module;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.security.authentication.Authentication;
import com.yifeng.security.authorization.Authorization;
import com.yifeng.security.users.User;
import com.yifeng.security.users.User.Status;
import com.yifeng.struts2.action.FormAction;
import com.yifeng.utils.JsonResultBuilder;

import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;

@Module(namespaceName = "security")
public class AuthAction extends FormAction {

	@Autowired
	UserService userService;

	@Operation(result = FILL)
	public String login() {

		return FILL;
	}

	@Autowired
	Authentication authentication;

	@Operation(result = JSON)
	public String doLogin() {
		String loginName = form.readString("loginName");
		String pwd = form.readString("password");

		Status status = userService.checkUserStatus(loginName, pwd);
		switch (status) {
		case Forbidden:
			setJson(JsonResultBuilder.success(false).msg("登录失败，该用户已被禁止访问。").json());
			break;
		case NotExists:
			setJson(JsonResultBuilder.success(false).msg("登录失败，不存在该用户。").json());
			break;
		case PasswordError:
			setJson(JsonResultBuilder.success(false).msg("登录失败，密码错误。").json());
			break;
		case Timeout:
			setJson(JsonResultBuilder.success(false).msg("登录失败，该密码已经过期，需要重新设置密码。").json());
			break;
		case Unknow:
			setJson(JsonResultBuilder.success(false).msg("登录失败，用户名密码错误。").json());
			break;
		case Success:
			User user = userService.findByLoginName(loginName);

			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setExcludes(new String[] { "roles", "teachings" });

			JSONObject jsonObject = JSONObject.fromObject(user, jsonConfig);

			setJson(JsonResultBuilder.success(true).msg("登录成功。").add("user", jsonObject).json());

			authentication.login(user.getId());
		default:
			break;
		}

		return JSON;
	}

	@Operation(result = GOTO)
	public String logout() {
		authentication.logout();
		setLocation("/");
		return GOTO;
	}
}
